// Tool Manager - 整合所有工具管理功能

import { DefaultToolRegistry } from './tool-registry';
import { DefaultToolExecutionEngine } from './tool-execution-engine';
import { FILE_OPERATION_TOOLS, PROCESS_MANAGEMENT_TOOLS, MEMORY_MANAGEMENT_TOOLS } from './tool-definitions';
import {
    ToolRegistry,
    ToolExecutionEngine,
    ToolResult,
    ToolExecutionContext,
    ToolCategory
} from './interfaces';

// 导入工具处理器
import {
    ReadFileHandler,
    SaveFileHandler,
    StrReplaceEditorHandler
} from '../tools/file-operations';

import {
    LaunchProcessHandler,
    KillProcessHandler,
    ReadProcessHandler,
    WriteProcessHandler,
    ListProcessesHandler
} from '../tools/process-management';

import {
    RememberHandler,
    MemoryRetrievalHandler
} from '../tools/memory-management';

/**
 * 工具管理器 - 统一管理所有工具
 */
export class ToolManager {
    private registry: ToolRegistry;
    private executionEngine: ToolExecutionEngine;
    private logger: any;
    private initialized: boolean = false;

    constructor(logger?: any) {
        this.logger = logger || console;
        this.registry = new DefaultToolRegistry(this.logger);
        this.executionEngine = new DefaultToolExecutionEngine(this.registry, this.logger);
    }

    /**
     * 初始化工具管理器
     */
    async initialize(): Promise<void> {
        if (this.initialized) {
            this.logger.warn('ToolManager is already initialized');
            return;
        }

        try {
            this.logger.info('Initializing ToolManager...');

            // 注册文件操作工具
            await this.registerFileOperationTools();

            // 注册进程管理工具
            await this.registerProcessManagementTools();

            // 注册记忆管理工具
            await this.registerMemoryManagementTools();

            // 注册其他工具类型...
            // await this.registerBrowserOperationTools();
            // await this.registerDiagnosticTools();
            // await this.registerWorkerAgentTools();

            this.initialized = true;
            this.logger.info(`ToolManager initialized successfully with ${this.registry.size()} tools`);

        } catch (error) {
            this.logger.error('Failed to initialize ToolManager:', error);
            throw error;
        }
    }

    /**
     * 执行工具
     */
    async executeTool(
        toolName: string,
        parameters: Record<string, any>,
        context?: ToolExecutionContext
    ): Promise<ToolResult> {
        if (!this.initialized) {
            throw new Error('ToolManager is not initialized. Call initialize() first.');
        }

        return await this.executionEngine.execute(toolName, parameters, context);
    }

    /**
     * 检查工具是否可用
     */
    isToolAvailable(toolName: string): boolean {
        return this.executionEngine.isToolAvailable(toolName);
    }

    /**
     * 获取所有可用工具
     */
    getAvailableTools(): string[] {
        return this.registry.getAllTools()
            .filter(tool => tool.metadata.isEnabled)
            .map(tool => tool.definition.name);
    }

    /**
     * 按类别获取工具
     */
    getToolsByCategory(category: ToolCategory): string[] {
        return this.registry.getToolsByCategory(category)
            .filter(tool => tool.metadata.isEnabled)
            .map(tool => tool.definition.name);
    }

    /**
     * 获取工具统计信息
     */
    getToolStats(): any {
        const allTools = this.registry.getAllTools();
        const stats = {
            totalTools: allTools.length,
            enabledTools: allTools.filter(t => t.metadata.isEnabled).length,
            disabledTools: allTools.filter(t => !t.metadata.isEnabled).length,
            categories: {} as Record<string, number>,
            mostUsedTools: [] as any[]
        };

        // 按类别统计
        for (const tool of allTools) {
            const category = tool.definition.category;
            stats.categories[category] = (stats.categories[category] || 0) + 1;
        }

        // 最常用的工具
        stats.mostUsedTools = allTools
            .sort((a, b) => b.metadata.callCount - a.metadata.callCount)
            .slice(0, 5)
            .map(tool => ({
                name: tool.definition.name,
                callCount: tool.metadata.callCount,
                lastCalled: tool.metadata.lastCalled
            }));

        return stats;
    }

    /**
     * 启用/禁用工具
     */
    setToolEnabled(toolName: string, enabled: boolean): boolean {
        return this.registry.setToolEnabled(toolName, enabled);
    }

    /**
     * 清理资源
     */
    async cleanup(): Promise<void> {
        this.logger.info('Cleaning up ToolManager...');

        // 清理进程管理器中的活动进程
        // 这里可以添加更多清理逻辑

        this.registry.clear();
        this.initialized = false;

        this.logger.info('ToolManager cleanup completed');
    }

    /**
     * 注册文件操作工具
     */
    private async registerFileOperationTools(): Promise<void> {
        this.logger.info('Registering file operation tools...');

        // 注册 read-file 工具
        this.registry.register(
            'read-file',
            FILE_OPERATION_TOOLS['read-file'],
            new ReadFileHandler()
        );

        // 注册 save-file 工具
        this.registry.register(
            'save-file',
            FILE_OPERATION_TOOLS['save-file'],
            new SaveFileHandler()
        );

        // 注册 str-replace-editor 工具
        this.registry.register(
            'str-replace-editor',
            FILE_OPERATION_TOOLS['str-replace-editor'],
            new StrReplaceEditorHandler()
        );

        this.logger.info('File operation tools registered successfully');
    }

    /**
     * 注册进程管理工具
     */
    private async registerProcessManagementTools(): Promise<void> {
        this.logger.info('Registering process management tools...');

        // 注册 launch-process 工具
        this.registry.register(
            'launch-process',
            PROCESS_MANAGEMENT_TOOLS['launch-process'],
            new LaunchProcessHandler()
        );

        // 注册 kill-process 工具
        this.registry.register(
            'kill-process',
            PROCESS_MANAGEMENT_TOOLS['kill-process'],
            new KillProcessHandler()
        );

        // 注册 read-process 工具
        this.registry.register(
            'read-process',
            PROCESS_MANAGEMENT_TOOLS['read-process'],
            new ReadProcessHandler()
        );

        // 注册 write-process 工具
        this.registry.register(
            'write-process',
            PROCESS_MANAGEMENT_TOOLS['write-process'],
            new WriteProcessHandler()
        );

        // 注册 list-processes 工具
        this.registry.register(
            'list-processes',
            PROCESS_MANAGEMENT_TOOLS['list-processes'],
            new ListProcessesHandler()
        );

        this.logger.info('Process management tools registered successfully');
    }

    /**
     * 注册记忆管理工具
     */
    private async registerMemoryManagementTools(): Promise<void> {
        this.logger.info('Registering memory management tools...');

        // 注册 remember 工具
        this.registry.register(
            'remember',
            MEMORY_MANAGEMENT_TOOLS['remember'],
            new RememberHandler()
        );

        // 注册 memory-retrieval 工具
        this.registry.register(
            'memory-retrieval',
            MEMORY_MANAGEMENT_TOOLS['memory-retrieval'],
            new MemoryRetrievalHandler()
        );

        this.logger.info('Memory management tools registered successfully');
    }
}
